package com.harry.apigeteway;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Harry
 * @date 2018/3/29 11:52
 */
public class AccessFilter extends ZuulFilter {

	private static Logger logger = LoggerFactory.getLogger(AccessFilter.class);

	/**
	 * 过滤器的类型 pre:可以在请求被路由之前调用 routing:在路由请求时被调用 post:在routing和error过滤器之后被调用
	 * error:处理请求时发生错误时被调用
	 * 
	 * @author Harry
	 *
	 * @Date 2018/3/29 14:08
	 */
	@Override
	public String filterType() {
		return "pre";
	}

	/**
	 * 过滤器的执行顺序： 数值越小优先级越高
	 * 
	 * @return
	 */
	@Override
	public int filterOrder() {
		return 0;
	}

	/**
	 * 判断该过滤器是否需要被执行
	 * 
	 * @return
	 */
	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {

		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		logger.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());

		Object accessToken = request.getParameter("accessToken");
		if (accessToken == null) {
			logger.warn("accessToken is empty");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			return null;
		}
		logger.info("access token ok");
		return null;
	}
}
